package model

import (
	"api/global"
	"api/types"
	"context"
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"log"
	"strings"
)

type VideoReleaseWeek3 struct {
	gorm.Model
	VideoTitle    string `gorm:"type:varchar(30);comment:视频标题;"`
	VideoSubTitle string `gorm:"type:varchar(50);comment:视频副标题;"`
	VideoAddress  string `gorm:"type:varchar(255);comment:视频播放地址;"`
	VideoViews    int    `gorm:"type:int(10);comment:视频观看次数;"`
	VideoType     int    `gorm:"type:int(10);comment:视频类型;"`
	VideoRegion   int    `gorm:"type:int(10);comment:视频地区;"`
	VideoImage    string `gorm:"type:varchar(255);comment:视频图片;"`
}

// 视频列表
func VideoList(data types.GetVideoListRequest) []VideoReleaseWeek3 {
	var list []VideoReleaseWeek3
	global.DB.Where("video_title like ?", "%"+data.Keyword+"%").Scopes(Paginate(data.Page, data.PageSize)).Find(&list)
	return list
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}
		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

// 视频详情
func VideoDetail(data types.VideoDetail) VideoReleaseWeek3 {
	var video VideoReleaseWeek3
	global.DB.Where("id = ?", data.VideoId).First(&video)
	return video
}

// 视频搜索(es)
func VideoSearch(data types.VideoSearch) VideoEsRequest {
	es := global.EsDB
	video := map[string]interface{}{
		"query": map[string]interface{}{
			"match": map[string]interface{}{
				"VideoTitle": data.VideoTitle,
			},
		},
	}
	marshal, _ := json.Marshal(video)
	res, err := es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex("video"),
		es.Search.WithBody(strings.NewReader(string(marshal))),
		es.Search.WithTrackTotalHits(true),
		es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("ERROR: %s", err)
	}
	defer res.Body.Close()
	fmt.Println("数据：：", res)

	var videoEs VideoEsRequest
	json.NewDecoder(res.Body).Decode(&videoEs)
	return videoEs
}

type VideoEsRequest struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore float64 `json:"max_score"`
		Hits     []struct {
			Index  string  `json:"_index"`
			Type   string  `json:"_type"`
			Id     string  `json:"_id"`
			Score  float64 `json:"_score"`
			Source struct {
				Id          int    `json:"id"`
				VideoTitle  string `json:"VideoTitle"`
				VideoDetail string `json:"video_detail"`
				VideoImage  string `json:"video_image"`
				Price       int    `json:"price"`
				Stock       int    `json:"stock"`
			} `json:"_source"`
		} `json:"hits"`
	} `json:"hits"`
}
